package org.webcamp.questionary.dao.impl;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXB;

import org.webcamp.questionary.dao.QuestionaryDao;
import org.webcamp.questionary.dto.Answer;
import org.webcamp.questionary.dto.Question;
import org.webcamp.questionary.dto.Questionary;
import org.webcamp.settings.services.SettingsService;

public class XmlQuestionaryDao implements QuestionaryDao {

	private static final String SETTING_NAME = "Path To Questionaries";

	private SettingsService settingsService;

	public void setSettingsService(SettingsService settingsService) {
		this.settingsService = settingsService;
	}

	@Override
	public List<Questionary> getAllQuestionaries() {
		List<Questionary> result = new ArrayList<>();
		String path = settingsService.loadSettings().getSetting(SETTING_NAME);
		if (path == null || path.length() == 0) {
			return result;
		}
		File dirWithQuestionaries = new File(path);
		if (!dirWithQuestionaries.exists() || !dirWithQuestionaries.isDirectory()) {
			return result;
		}
		File[] files = dirWithQuestionaries.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return name.endsWith(".xml");
			}
		});

		for (File questionaryFile : files){
			Questionary q = JAXB.unmarshal(questionaryFile, Questionary.class);
			result.add(q);
		}
		return result;
	}

	public static void main(String[] args) {
		List<Question> questions = new ArrayList<>();
		for (int j = 0; j < 5; j++) {
			Question q = new Question();
			q.setText("Test question " + j);
			List<Answer> answers = new ArrayList<>();
			Answer a1 = new Answer();
			a1.setCorrect(true);
			a1.setText("Correct answer");
			Answer a2 = new Answer();
			a2.setCorrect(false);
			a2.setText("Incorrect answer");
			answers.add(a1);
			answers.add(a2);
			q.setAnswers(answers);
			questions.add(q);
		}
		Questionary questionary = new Questionary();
		questionary.setDescription("Description for Test questionary ");
		questionary.setName("Test questionary");
		questionary.setQuestions(questions);

		JAXB.marshal(questionary, new File("c:/temp/questionary.xml"));
		// XmlQuestionaryDao dao = new XmlQuestionaryDao();

		Questionary q1 = (Questionary) JAXB.unmarshal(new File("c:/temp/questionary.xml"), Questionary.class);
		System.out.println(q1);

		// dao.parseQuestionary(new
		// File("C:/work/workspace.trating.adv2/xquesty/questionaries/qwe1.xml"));
	}

}
